package com.fuershiye.woman.monitor.dao;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fuershiye.woman.monitor.beans.IdName;
import com.fuershiye.woman.monitor.model.Forms;
import com.google.common.collect.Lists;

@Repository("formsDao")
@SuppressWarnings("unchecked")
public class FormsDao {

    @Autowired
    private HibernateDao hibernateDao;

    public void save(Forms forms){
        hibernateDao.save(forms);
    }

    public void delete(Long id) {
        String sql = "update Forms set status = 0 where id = ?";
        SQLQuery query = hibernateDao.getSqlQuery(sql).addEntity(Forms.class);
        query.setLong(0, id);
        query.executeUpdate();
    }

    public Forms get(Long id) {
    	return hibernateDao.getById(Forms.class,id);
    }

    @SuppressWarnings("unchecked")
	public List<Forms> getPage(String name, Integer page, Integer pageSize) {

    	StringBuffer sb = new StringBuffer("from Forms where 1=1 ");
    	if(StringUtils.isNotBlank(name)){
    		sb.append("and name like:name ");
    	}
		if(page==null||page==0){
			page= 1;
		}
		if(pageSize==null||pageSize==0){
			pageSize= 30;
		}
		sb.append("ORDER BY id DESC");
    	Query query = hibernateDao.getQuery(sb.toString());
    	
    	if(StringUtils.isNotBlank(name)){
            query.setString("name","%" + name + "%");
    	}
    	//size 		10
    	//page 		1,	 2,		3
    	//return 	0-9, 10-19,	20-29
    	query.setFirstResult((page-1)*pageSize);
    	query.setMaxResults(page*pageSize-1);
    	
        return query.list();
    }

    @SuppressWarnings("unchecked")
    public List<IdName> getAllNames() {

        List<IdName> result = Lists.newArrayList();
        
        String hql = "select id,name from forms where status = 1 ORDER BY id DESC";
        Query query = hibernateDao.getSqlQuery(hql);
        List<Object[]> queryResult = query.list();
        
        for (Object[] fields : queryResult) {
        	IdName idAndName = new IdName();
        	idAndName.setId(fields[0] == null? 0:Long.parseLong(fields[0].toString()));
        	idAndName.setName(fields[1] == null? "":fields[1].toString());
    	  	result.add(idAndName);
		}
	  	return result;
    }
    
}
